package org.baiduai.face;

import com.alibaba.fastjson2.JSONObject;
import okhttp3.*;
import org.springframework.lang.NonNull;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Packge org.baiduai.face
 * @Autor naibin.lin
 * @Description
 * @Version 1.0
 * @Date 2022-11-28 15:34
 */
public class OkHttpSender {

    //1、异步get请求
    public void getAsyncRequest(String url, Map<String, String> headerMap) {
        //1、创建OkHttpClient对象
        OkHttpClient client = new OkHttpClient(new OkHttpClient.Builder());
        //通常使用
        // OkHttpClient.Builder client = new OkHttpClient.Builder(); //里面存在许多默认的配置
        //2、创建Request对象，设置一个URL地址，设置请求方式

        Request.Builder builder = new Request.Builder();
        builder.url(url).get();
        // header
        if (null != headerMap && headerMap.size() > 0) {
            Iterator<Map.Entry<String, String>> iterator = headerMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> entry = iterator.next();
                builder.addHeader(entry.getKey(), entry.getValue());
            }
        }
        //
        //3、创建一个call对象，参数为 request 请求对象
        Call call = client.newCall(builder.build());
        //4、将请求加入调度，重写回调方法
        call.enqueue(new Callback() {
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                // 判断是否响应成功
                if (response.code() == 200) {
                    // String string = response.body().string();
                    // 获取 Json 字符串，后续解析使用
                }
                System.out.println("调用成功：：" + response.body().string());
            }

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }
        });
    }

    //1、异步get请求
    public String getSyncRequest(String url, Map<String, String> headerMap) {
        //1、创建OkHttpClient对象
        OkHttpClient client = new OkHttpClient(new OkHttpClient.Builder());
        //通常使用
        //2、创建Request对象，设置一个URL地址，设置请求方式

        Request.Builder builder = new Request.Builder();
        builder.url(url).get();
        // header
        if (null != headerMap && headerMap.size() > 0) {
            Iterator<Map.Entry<String, String>> iterator = headerMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> entry = iterator.next();
                builder.addHeader(entry.getKey(), entry.getValue());
            }
        }
        //
        //3、创建一个call对象，参数为 request 请求对象
        Call call = client.newCall(builder.build());

        try {
            Response response = call.execute();
            if (response.isSuccessful()) {
                String ret = response.body().string();
                return ret;
            } else {
                throw new RuntimeException("调用失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    //1、异步get请求
    public String syncRequest(String url, String jsonParam) {
        //1、创建OkHttpClient对象
        OkHttpClient client = new OkHttpClient(new OkHttpClient.Builder());
        //通常使用
        //2、创建Request对象，设置一个URL地址，设置请求方式
        RequestBody requestBody = RequestBody.create(jsonParam, MediaType.parse("application/json"));
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        // header

        //3、创建一个call对象，参数为 request 请求对象
        Call call = client.newCall(request);

        try {
            Response response = call.execute();
            if (response.isSuccessful()) {
                String ret = response.body().string();
                return ret;
            } else {
                throw new RuntimeException("调用失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void main(String[] args) {
        OkHttpSender sender = new OkHttpSender();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("cmd", "0");
        String ret = sender.syncRequest("http://172.16.10.16:1880/api/device/door/set_state", jsonObject.toString());
        /////
        System.out.println("调用开门接口：" + ret);
    }
}